package com.none.Plugin.Beacon;
import java.util.List;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.annotation.SuppressLint;
import android.util.Log;
import android.widget.Toast;

import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;



@SuppressLint("ShowToast")
public class ibeacon extends CordovaPlugin {



	public static final String staticUuid="proximityUUID";
	public static final String staticMajor="major";
	public static final String staticMinor="minor";
	public static final String staticId="identifier";
	private static final String TAG = "ListBeaconsActivity";
	private BeaconManager beaconManager;
	private JSONArray jsonBeacon;
	
	private CallbackContext callbackContextThis;

	@SuppressLint("ShowToast")
	public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) throws JSONException {
		callbackContextThis = callbackContext;
		JSONArray messageTemp = args.getJSONArray(0);
		jsonBeacon = messageTemp;
		
		Log.e(TAG, messageTemp.toString());
		Log.e(TAG, "连接服务成功");
		if (action.equals("startMonitorBeaconLocate")) {
			beaconManager = new BeaconManager(this.cordova.getActivity());
			beaconManager.setRangingListener(new BeaconManager.RangingListener() {
				@Override
				public void onBeaconsDiscovered(Region region, final List<Beacon> beacons) {
//					  Log.d(TAG, "Ranged beacons: " + beacons);
				}
			});
			//开始监听 beacon Monitor
			beaconManager.setMonitoringListener(new BeaconManager.MonitoringListener() {
				@Override
				//进入beacon 的范围
				public void onExitedRegion(Region arg0) {

					 int major =0;
					 int  minor =0;
					Log.e(TAG, "beacon退出");	

					major=arg0.getMajor();
					String uuid = arg0.getProximityUUID();
					minor=arg0.getMinor();
					Log.e(TAG,"退出 minor是"+minor+"uuid是"+uuid+"major是"+major);
				
					
                    
				}
				//离开beacon 的范围
				public void onEnteredRegion(Region arg0, List<Beacon> arg1) {

					 int major =0;
					 int  minor =0;
					for(int i=0;i<arg1.size();i++){

						Beacon  beacon = arg1.get(i);
						major=beacon.getMajor();
						String uuid = beacon.getProximityUUID();
						minor=beacon.getMinor();
		
						Log.e(TAG,"进入minor是"+minor+"uuid是"+uuid+"major是"+major);
						JSONObject jsonTemp =	this.getJsonObjectWithBeaconMessage(uuid,String.valueOf(major),String.valueOf(minor));
						Log.e(TAG, "进入的时"+jsonTemp.toString());
						// callbackContextThis.success(jsonTemp);
						PluginResult result;
						result = new PluginResult(PluginResult.Status.OK,
								  jsonTemp);
					    result.setKeepCallback(true);
						  
					    callbackContextThis.sendPluginResult(result);
					}
				}
				// get jsonObject with becon的uuid ,major,minor
				private JSONObject getJsonObjectWithBeaconMessage(final String uuidInput, final String majorInput,final String minorInput)
			     {
					for (int i=0;i<jsonBeacon.length();i++)
			   	     {
						try {
						JSONObject jsonObjectTemp = jsonBeacon.getJSONObject(i);
							Log.e(TAG, jsonObjectTemp.toString());
				
							String uuidstr=jsonObjectTemp.getString(staticUuid);
							String majorstr=jsonObjectTemp.getString(staticMajor);
							String minorstr=jsonObjectTemp.getString(staticMinor);
							
							 String InputUUidLowCase= uuidInput.toLowerCase();
							 String uuidstrLowCase = uuidstr.toLowerCase();
							
							if (InputUUidLowCase.equalsIgnoreCase(uuidstrLowCase) && majorstr.equals(majorInput)&& minorstr.equals(minorInput))
							{
								Log.e(TAG, "getJsonObjectEqual");
								return jsonObjectTemp;
							}
							
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							 return null;
						}
			    	 }
			    	 return null;
			     }
			});
		
			  if (!beaconManager.hasBluetooth()) {
				  callbackContextThis.error("硬件不支持监听功能");
			    }
			  else if(!beaconManager.isBluetoothEnabled())
			  {
				  Toast.makeText(this.cordova.getActivity(), "请打开蓝牙", 3000).show();
				  // 
				  callbackContextThis.error("请打开蓝牙");
			  }
			  else
			  {
				  this.connectToService(messageTemp);
				  return true;
			  }
		}
		return false;
	}

		
	private void connectToService( final JSONArray Arrayessage ) {

		beaconManager.connect(new BeaconManager.ServiceReadyCallback() {

			@Override
			public void onServiceReady() {
				try {
					Log.e(TAG, "开始连接服务成功");
				
					for(int i=0;i<Arrayessage.length();i++){
					  
						JSONObject	jsonObjectTemp=Arrayessage.getJSONObject(i);
						
						Log.e(TAG, jsonObjectTemp.toString());
    					String uuidstr=jsonObjectTemp.getString(staticUuid);
    					String majorstr=jsonObjectTemp.getString(staticMajor);
						String minorstr=jsonObjectTemp.getString(staticMinor);
						String identistr=jsonObjectTemp.getString(staticId);
					
						Region ALL_ESTIMOTE_BEACONS2_REGION = new Region(identistr, uuidstr, Integer.valueOf(majorstr), Integer.valueOf(minorstr));
						beaconManager.startRanging(ALL_ESTIMOTE_BEACONS2_REGION);
						beaconManager.startMonitoring(ALL_ESTIMOTE_BEACONS2_REGION);
					}	
					jsonBeacon.getJSONObject(0);
					
					
				}
		        catch (Exception e) {
					Log.e(TAG, " 不能连接", e);
					callbackContextThis.error("ibeacon蓝牙连接失败"+e);

				}
			}
		});
	}

}




